package com.qishi.myServletContainer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer1 {

    private final String SHUTDOWN_COMMAND = "/SHUTDOWN";

    private boolean shutdown = false;

    public static void main(String[] args) {

    }

    public void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            serverSocket = new ServerSocket(port,1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            //强制退出，无论程序是否还在执行中
            System.exit(1);
        }

        while (!shutdown) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();

                //创建一个request对象并且解析请求里的流数据
                Request request = new Request(input);
                request.parse();

                //创建一个Response对象
                Response response = new Response(output);
                response.setRequest(request);

                //检查请求里的url是请求servlet还是静态资源
                if(request.getUri().startsWith("/servlet/")) {
                    ServletProcessor1 servletProcessor1 = new ServletProcessor1();
                    servletProcessor1.process(request, response);
                }else {
                    StaticResourceProcessor processor = new StaticResourceProcessor();
                    processor.process(request,response);
                }
                //关闭socket
                socket.close();

                shutdown = request.getUri().equals("SHUTDOWN_COMMAND");
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
}
